package cn.bookcycle.order.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bookcycle.order.constant.AppConstant;
import cn.bookcycle.order.constant.BusinessConstant;
import cn.bookcycle.order.constant.CommonConstant;
import cn.bookcycle.order.constant.DBConstant;
import cn.bookcycle.order.pojo.DBManipulateBO;
import cn.bookcycle.order.util.DaoUtil;
import cn.bookcycle.order.util.DataUtil;
import cn.bookcycle.order.util.OrderId;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 订单微服务
 *
 * @author liufenglin
 * @date 2018年4月3日
 */
@Controller
public class OrderMS {
	private static final Logger logger = LoggerFactory.getLogger(OrderMS.class);
	
	/**
	 * 接收POST请求调用，记录订单信息，并返回订单号
	 * 
	 * @param requestBody
	 *            POST请求体，存放订单信息的JSON数据
	 * @return 32位的{@link String}类型订单号
	 */
	@RequestMapping(value = "saveorder", method = RequestMethod.POST)
	@ResponseBody
	public String saveOrder(@RequestBody(required = false) String requestBody) {
		logger.warn("requestBody:{}", requestBody);
		// 调用者的ID
		String appId = null;
		// 返回给调用者的消息
		String result = null;
		// 操纵数据库微服务的对象
		DBManipulateBO manipulate = null;
		// 系统生成的32位订单ID
		String orderId = OrderId.generateOrderId32();
		JSONObject jsonObject = null;
		// requestBody是否为标准json格式的判断标志
		boolean isJson = true;
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, CommonConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("请求体URL解码异常！！！ requestBody:{}", requestBody);
			}

			try {
				// 解析发过来的JSON数据，并添加orderId参数
				jsonObject = JSONObject.fromObject(requestBody);
				jsonObject.put(BusinessConstant.ORDER_ID, orderId);
			} catch (JSONException e) {
				isJson = false;
				logger.warn("saveOrder requestBody解析为JSON异常！！");
			}

			if (isJson) {
				if (jsonObject.containsKey(BusinessConstant.APP_ID)) {
					appId = jsonObject.getString(BusinessConstant.APP_ID);
					if (AppConstant.list.contains(appId)) {
						manipulate = new DBManipulateBO();
						manipulate.setDbName(DBConstant.DB_VALUE);
//						manipulate.setTabName(DBConstant.TAB_DEFAULT_VALUE);
						manipulate.setTabName(appId);
						manipulate.setMethod(DBConstant.INSERT);
						manipulate.setObject(jsonObject);

						// 操纵数据库
						result = DaoUtil.dbManipulate(manipulate);
						if (CommonConstant.SUCCESS.equals(result)) {
							// 把订单号返回给调用者
							result = orderId;
						} else {}
					} else {
						result = BusinessConstant.APPID_ERR;
					} // end if (AppConstant.list.contains(appId)) ... else ...
				} else {
					result = BusinessConstant.NO_APPID;
				} // end if (jsonObject.containsKey(BusinessConstant.APP_ID)) ... else ...
			} else {
				result = BusinessConstant.JSON_IS_ERR;
			} // end if (isJson) ... else ...
		} else {
			result = BusinessConstant.BODY_IS_NULL;
			logger.info("requestBody 为空！！！");
		} // end if (requestBody != null) else ...
		logger.warn("返回给请求getorder者的result:{}", result);
		return result;
	}

	/**
	 * 根据订单号查询订单的全部信息
	 * 
	 * @param requestBody
	 *            JSON格式数据，包含orderId等参数
	 * @return JSONArray格式的订单数据
	 */
	@RequestMapping(value = "getorder", method = RequestMethod.POST)
	@ResponseBody
	public String getOrder(@RequestBody(required = false) String requestBody) {
		logger.warn("requestBody:{}", requestBody);
		// 调用者的ID
		String appId = null;
		// 返回给调用者的消息
		String result = null;
		// 操纵数据库微服务的对象
		DBManipulateBO manipulate = null;
		JSONObject jsonObject = null;
		// requestBody是否为标准json格式的判断标志
		boolean isJson = true;
		
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, CommonConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("请求体URL解码异常！！！ requestBody:{}", requestBody);
			}
			try {
				// 解析发过来的JSON数据，并添加orderId参数
				jsonObject = JSONObject.fromObject(requestBody);
			} catch (JSONException e) {
				isJson = false;
				logger.warn("getOrder requestBody解析为JSON异常！！");
			}
			if (isJson) {
				if (jsonObject.containsKey(BusinessConstant.APP_ID)) {
					appId = jsonObject.getString(BusinessConstant.APP_ID);
					if (AppConstant.list.contains(appId)) {
						
						manipulate = new DBManipulateBO();
						manipulate.setDbName(DBConstant.DB_VALUE);
//						manipulate.setTabName(DBConstant.TAB_DEFAULT_VALUE);
						manipulate.setTabName(appId);
						manipulate.setMethod(DBConstant.FIND);
						
						if (jsonObject.containsKey(DBConstant.SORT)) {
							manipulate.setSort(jsonObject.getString(DBConstant.SORT));
							jsonObject.remove(DBConstant.SORT);
						}
						if (jsonObject.containsKey(DBConstant.SORT_ORDER)) {
							manipulate.setSortOrder(jsonObject.getInt(DBConstant.SORT_ORDER));
							jsonObject.remove(DBConstant.SORT_ORDER);
						}
						if (jsonObject.containsKey(DBConstant.SKIP)) {
							manipulate.setSkip(jsonObject.getInt(DBConstant.SKIP));
							jsonObject.remove(DBConstant.SKIP);
						} 
						if (jsonObject.containsKey(DBConstant.LIMIT)) {
							manipulate.setLimit(jsonObject.getInt(DBConstant.LIMIT));
							jsonObject.remove(DBConstant.LIMIT);
						}
						
						manipulate.setObject(jsonObject);

						// 操纵数据库
						result = DaoUtil.dbManipulate(manipulate);
					} else {
						result = BusinessConstant.APPID_ERR;
					} // end if (AppConstant.list.contains(appId)) ... else ...
				} else {
					result = BusinessConstant.NO_APPID;
				} // end if (jsonObject.containsKey(BusinessConstant.APP_ID)) ... else ...
				
			} else {
				result = BusinessConstant.JSON_IS_ERR;
			} // end if (isJson) ... else ...

		} else {
			result = BusinessConstant.BODY_IS_NULL;
		} // end if (requestBody != null) else ...
		logger.warn("返回给请求saveorder调用者的result:{}", result);
		return result;
	}

	@RequestMapping(value = "updateorder", method = RequestMethod.POST)
	@ResponseBody
	public String updateOrder(@RequestBody(required = false) String requestBody) {
		logger.warn("requestBody:{}", requestBody);
		// 调用者的ID
		String appId = null;
		// 返回给调用者的消息
		String result = null;
		// 查找指定订单的订单号
		String orderId = null;
		// 操纵数据库微服务的对象
		DBManipulateBO manipulate = null;
		JSONObject jsonObject = null;
		JSONArray jsonArrayFromDB = null;
		JSONObject jsonObject4Find = null;
		JSONObject jsonObject4Save = null;
		// requestBody是否为标准json格式的判断标志
		boolean isJson = true;
		// 根据orderId获取的信息是否为标准JSONArray格式的判断标志
		boolean isJsonArray = true;
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, CommonConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("请求体URL解码异常！！！ requestBody:{}", requestBody);
			}

			try {
				// 解析发过来的JSON数据，并添加orderId参数
				jsonObject = JSONObject.fromObject(requestBody);
				orderId = jsonObject.getString(BusinessConstant.ORDER_ID);
			} catch (JSONException e) {
				isJson = false;
				logger.warn("updateOrder requestBody解析为JSON异常！！");
			}
			
			if (isJson) {
				if (jsonObject.containsKey(BusinessConstant.APP_ID)) {
					appId = jsonObject.getString(BusinessConstant.APP_ID);
					if (AppConstant.list.contains(appId)) {
						jsonObject4Find = new JSONObject();
						jsonObject4Find.put(BusinessConstant.ORDER_ID, orderId);
						
						manipulate = new DBManipulateBO();
						manipulate.setDbName(DBConstant.DB_VALUE);
//						manipulate.setTabName(DBConstant.TAB_DEFAULT_VALUE);
						manipulate.setTabName(appId);
						manipulate.setMethod(DBConstant.FIND);
						manipulate.setObject(jsonObject4Find);
						
						// 操纵数据库
						String info = DaoUtil.dbManipulate(manipulate);
						logger.info("updateOrder 根据orderId查询到的信息是:{}", info);

						try {
							jsonArrayFromDB = JSONArray.fromObject(info);
						} catch (JSONException e) {
							isJsonArray = false;
							logger.warn("updateOrder 解析JSONArray异常！！");
						}

						if (isJsonArray) {
							// 参考调用者发过来的jsonObject 对 jsonArrayFromDB的jsonObject 进行修改
							jsonObject4Save = DataUtil.updateJSONObject(jsonObject, jsonArrayFromDB.getJSONObject(0));
							// 保存更新后的JSON数据
							manipulate.setMethod(DBConstant.INSERT);
							manipulate.setObject(jsonObject4Save);
							// 操纵数据库
							result = DaoUtil.dbManipulate(manipulate);
						} else {
							result = BusinessConstant.ORDER_ID_IS_INVALID;
						} // end if (isJsonArray) ... else ...
						
					} else {
						result = BusinessConstant.APPID_ERR;
					} // end if (AppConstant.list.contains(appId)) ... else ...
				} else {
					result = BusinessConstant.NO_APPID;
				} // end if (jsonObject.containsKey(BusinessConstant.APP_ID)) ... else ...
				
			} else {
				result = BusinessConstant.BODY_IS_NULL;
			} // end if (isJson) ... else

		} else {
			result = BusinessConstant.BODY_IS_NULL;
		} // end if (requestBody != null) else ...
		return result;
	}

	@RequestMapping(value = "deleteorder", method = RequestMethod.POST)
	@ResponseBody
	public String deleteorder(@RequestBody(required = false) String requestBody) {
		logger.warn("requestBody:{}", requestBody);
		// 返回给调用者的消息
		String result = null;
		// 调用者的ID
		String appId = null;
		// 操纵数据库微服务的对象
		DBManipulateBO manipulate = null;
		String id = null;
		JSONObject jsonObject = null;
		JSONArray jsonArray =null;
		// requestBody是否为标准json格式的判断标志
		boolean isJson = true;
		// 根据orderId获取的信息是否为标准JSONArray格式的判断标志
		boolean isJsonArray = true;
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, CommonConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("请求体URL解码异常！！！ requestBody:{}", requestBody);
			}
			
			try {
				// 解析发过来的JSON数据，并添加orderId参数
				jsonObject = JSONObject.fromObject(requestBody);
			} catch (JSONException e) {
				isJson = false;
				logger.warn("getOrder requestBody解析为JSON异常！！");
			}
			
			if (isJson) {
				if (jsonObject.containsKey(BusinessConstant.APP_ID)) {
					appId = jsonObject.getString(BusinessConstant.APP_ID);
					if (AppConstant.list.contains(appId)) {
						manipulate = new DBManipulateBO();
						manipulate.setDbName(DBConstant.DB_VALUE);
						manipulate.setTabName(appId);
						manipulate.setMethod(DBConstant.FIND);
						manipulate.setObject(jsonObject);

						// 操纵数据库
						result = DaoUtil.dbManipulate(manipulate);

						try {
							jsonArray = JSONArray.fromObject(result);
							jsonObject = jsonArray.getJSONObject(0);
							id = jsonObject.getString(BusinessConstant.ID);
						} catch (JSONException e) {
							isJsonArray = false;
							logger.warn("deleteorder 解析JSONArray异常！！！ 被解析的参数是：{}", result);
						}

						if (isJsonArray) {
							// 新建JSONObject用于删除
							jsonObject = new JSONObject();
							jsonObject.put(BusinessConstant.ID, id);
							// 封装操作数据库的对象
							manipulate.setMethod(DBConstant.REMOVE);
							manipulate.setObject(jsonObject);
							// 操纵数据库
							result = DaoUtil.dbManipulate(manipulate);
						} else {
							result = BusinessConstant.ORDER_ID_IS_INVALID;
						} // end if (isJsonArray) ... else ...

					} else {
						result = BusinessConstant.APPID_ERR;
					} // end if (AppConstant.list.contains(appId)) ... else ...
				} else {
					result = BusinessConstant.NO_APPID;
				} // if (jsonObject.containsKey(BusinessConstant.APP_ID)) ... else ...
				
			} else {
				result = BusinessConstant.JSON_IS_ERR;
			} // end if (isJson) ... else ...
		} else {
			result = BusinessConstant.BODY_IS_NULL;
		} // end if (requestBody != null) ... else ...
		return result;
	}

}
